package com.alphas.xixibackendalphas.service.impl;

import com.alphas.xixibackendalphas.common.StatusCode;
import com.alphas.xixibackendalphas.exception.BusinessException;
import com.alphas.xixibackendalphas.mapper.UserMapper;
import com.alphas.xixibackendalphas.model.domain.User;
import com.alphas.xixibackendalphas.service.UserService;
import com.alphas.xixibackendalphas.utils.AlgorithmUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.math3.util.Pair;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.alphas.xixibackendalphas.common.StatusCode.*;
import static com.alphas.xixibackendalphas.constant.Constant.ADMIN_ROLE;
import static com.alphas.xixibackendalphas.constant.Constant.USER_LOGIN_STATE;

/**
* @author Alphas
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-06-12 15:11:19
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    //加密用的盐值
    private static final String SALT = "alphas";

    @Override
    public Long userRegister(String userAccount, String userPassword, String checkPassword) {
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(NULL_ERROR);
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(PARAM_ERROR);
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(PARAM_ERROR);
        }
        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(PARAM_ERROR);
        }
        // 密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(PARAM_ERROR);
        }
        // 账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(PARAM_ERROR);
        }

        // 密码加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 3. 插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        boolean saveResult = this.save(user);
        if (!saveResult) {
            throw new BusinessException(StatusCode.UNKNOWN_ERROR);
        }
        return user.getId();
    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(NULL_ERROR);
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(PARAM_ERROR);
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(PARAM_ERROR);
        }
        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(PARAM_ERROR);
        }

        //校验密码
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", userAccount);
        queryWrapper.eq("user_password", encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(StatusCode.NOT_FOUND);
        }
        //用户存在，返回用户信息(脱敏)
        User safetyUser = getSafetyUser(user);
        request.getSession().setAttribute(USER_LOGIN_STATE, safetyUser);
        return safetyUser;
    }

    @Override
    public User getSafetyUser(User originUser) {
        if (originUser == null) {
            return null;
        }
        User safetyUser = new User();
        safetyUser.setId(originUser.getId());
        safetyUser.setUserName(originUser.getUserName());
        safetyUser.setUserAccount(originUser.getUserAccount());
        safetyUser.setAvatarUrl(originUser.getAvatarUrl());
        safetyUser.setGender(originUser.getGender());
        safetyUser.setEmail(originUser.getEmail());
        safetyUser.setUserRole(originUser.getUserRole());
        safetyUser.setUserStatus(originUser.getUserStatus());
        safetyUser.setCreateTime(originUser.getCreateTime());
        return safetyUser;
    }

    @Override
    public List<User> userSearch(HttpServletRequest request, String username) {
        if (isAdmin(request)){
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.like("user_name",username);
            List<User> list = this.list(userQueryWrapper);
            return list.stream().map(this::getSafetyUser).collect(Collectors.toList());
        }
        throw new BusinessException(UNAUTHORIZED);
    }

    @Override
    public Boolean deleteUser(HttpServletRequest request, long userId) {
        if (isAdmin(request)){
            return this.removeById(userId);
        }
        throw new BusinessException(UNAUTHORIZED);
    }

    @Override
    public User getCurrentUserInfo(HttpServletRequest request) {
        Object attribute = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) attribute;
        Long id = user.getId();
        User byId = userMapper.selectById(id);
        return this.getSafetyUser(byId);
    }

    /**
     * 用户注销
     * @param request 前端请求
     * @return 是否成功
     */
    @Override
    public Integer userLogout(HttpServletRequest request) {
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 0;
    }

    /**
     * 根据标签搜索用户(memory查询)
     * @param tagNameList 用户要拥有的标签
     * @return 用户列表
     */
    @Override
    public List<User> searchUserByTags(List<String> tagNameList) {
        //  memory query
//        1.先查询所有用户
//        Long start = System.currentTimeMillis();
        QueryWrapper<User> queryWrapper1 = new QueryWrapper<>();
        List<User> userList1 = userMapper.selectList(queryWrapper1);
        Gson gson = new Gson();
        //2.在内存中判断是否包含需要的标签
        return userList1.stream().filter(user -> {
            String userTags = user.getUserTags();
            if (StringUtils.isAnyBlank(userTags)) {
                return false;
            }
            Set<String> tempTagNameSet = gson.fromJson(userTags, new TypeToken<Set<String>>() {
            }.getType());
            tempTagNameSet = Optional.ofNullable(tempTagNameSet).orElse(new HashSet<>());
            for (String tag : tagNameList) {
                if (!tempTagNameSet.contains(tag)) {
//                    throw new BusinessException(NULL_ERROR);
                    return false;
                }
            }
            return true;
        }).map(this::getSafetyUser).collect(Collectors.toList());
//        log.info("memory query: " + (System.currentTimeMillis()-start));
    }

    /**
     * 修改用户信息
     * @param user 传入的修改信息
     * @param request 网页请求
     * @return 影响的用户数
     */
    @Override
    public Integer updateUser(User user, HttpServletRequest request) {
        //0.判断是否真的传入了修改值
        //1.判断是否为管理员
        //不是管理员拿到当前用户登录信息
        User userLogin = getUserLogin(request);
        //同当前用户id和要修改的用户id进行比较
        if (!isAdmin(request) && !userLogin.getId().equals(user.getId())){
            throw new BusinessException(UNAUTHORIZED);
        }
        //2. 查询用户是否存在
        User oldUser = userMapper.selectById(user.getId());
        //不存在,抛出异常
        if (oldUser == null) {
            throw new BusinessException(NULL_ERROR);
        }
        // 检查是否有要更新的属性值
        if (oldUser.getUserName().equals(user.getUserName()) && oldUser.getEmail().equals(user.getEmail())
         && oldUser.getUserTags().equals(user.getUserTags()) && oldUser.getUserRole().equals(user.getUserRole())
        && oldUser.getAvatarUrl().equals(user.getAvatarUrl()) && oldUser.getPhone().equals(user.getPhone())) {
            throw new BusinessException(NULL_ERROR);
        }
        //更新数据
        oldUser.setUserName(user.getUserName() != null ? user.getUserName() : oldUser.getUserName());
        oldUser.setEmail(user.getEmail() != null ? user.getEmail() : oldUser.getEmail());
        oldUser.setUserTags(user.getUserTags() != null ? user.getUserTags() : oldUser.getUserTags());
        oldUser.setUserRole(user.getUserRole() != null ? user.getUserRole() : oldUser.getUserRole());
        oldUser.setAvatarUrl(user.getAvatarUrl() != null ? user.getAvatarUrl() : oldUser.getAvatarUrl());
        oldUser.setPhone(user.getPhone() != null ? user.getPhone() : oldUser.getPhone());

        //否则返回修改影响的用户数
        return userMapper.updateById(oldUser);
    }

    /**
     * 推荐用户信息
     * @param pageNum 第几页
     * @param request 网页请求
     * @param pageSize 分页大小
     * @return 分页后的用户列表
     */
    @Override
    public Page<User> userRecommend(HttpServletRequest request, int pageNum, int pageSize) {
        //更改格式
        User userLogin = getUserLogin(request);
        String redisKey = String.format("yupao:user:recommed:%s", userLogin.getId());
        //如果有缓存直接读取缓存
        Page<User> userPage = (Page<User>) redisTemplate.opsForValue().get(redisKey);
        if (userPage != null) {
            return userPage;
        }
        //没有缓存则查询数据库
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        //写缓存
        redisTemplate.opsForValue().set(redisKey, userPage, 30000, TimeUnit.MILLISECONDS);
        return this.page(new Page<>(pageNum, pageSize), userQueryWrapper);
    }

    /**
     * 根据标签搜索用户(SQL查询)
     *
     * @param tagNameList 用户要拥有的标签
     * @return 用户列表
     */
    @Deprecated
    public List<User> searchUserByTagsBySQL(List<String> tagNameList) {
        if (CollectionUtils.isEmpty(tagNameList)){
            throw new BusinessException(PARAM_ERROR);
        }
//        sql query
//        long start = System.currentTimeMillis();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //拼接and查询
        for (String tagName : tagNameList) {
            queryWrapper.like("user_tags",tagName);
        }
        List<User> userList = userMapper.selectList(queryWrapper);
//        log.info("sql query: " + (System.currentTimeMillis()-start));
        return userList.stream().map(this::getSafetyUser).collect(Collectors.toList());
    }

    public boolean isAdmin(HttpServletRequest request){
        Object attribute = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) attribute;
        Integer userRole = user.getUserRole();
        return userRole == ADMIN_ROLE;
    }

    @Override
    public List<User> matchUsers(long num, User loginUser) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "tags");
        queryWrapper.isNotNull("tags");
        List<User> userList = this.list(queryWrapper);
        String tags = loginUser.getUserTags();
        Gson gson = new Gson();
        List<String> tagList = gson.fromJson(tags, new TypeToken<List<String>>() {
        }.getType());
        // 用户列表的下标 => 相似度
        List<Pair<User, Long>> list = new ArrayList<>();
        // 依次计算所有用户和当前用户的相似度
        for (int i = 0; i < userList.size(); i++) {
            User user = userList.get(i);
            String userTags = user.getUserTags();
            // 无标签或者为当前用户自己
            if (StringUtils.isBlank(userTags) || user.getId() == loginUser.getId()) {
                continue;
            }
            List<String> userTagList = gson.fromJson(userTags, new TypeToken<List<String>>() {
            }.getType());
            // 计算分数
            long distance = AlgorithmUtils.minDistance(tagList, userTagList);
            list.add(new Pair<>(user, distance));
        }
        // 按编辑距离由小到大排序
        List<Pair<User, Long>> topUserPairList = list.stream()
                .sorted((a, b) -> (int) (a.getValue() - b.getValue()))
                .limit(num)
                .collect(Collectors.toList());
        // 原本顺序的 userId 列表
        List<Long> userIdList = topUserPairList.stream().map(pair -> pair.getKey().getId()).collect(Collectors.toList());
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.in("id", userIdList);
        // 1, 3, 2
        // User1、User2、User3
        // 1 => User1, 2 => User2, 3 => User3
        Map<Long, List<User>> userIdUserListMap = this.list(userQueryWrapper)
                .stream()
                .map(user -> getSafetyUser(user))
                .collect(Collectors.groupingBy(User::getId));
        List<User> finalUserList = new ArrayList<>();
        for (Long userId : userIdList) {
            finalUserList.add(userIdUserListMap.get(userId).get(0));
        }
        return finalUserList;
    }

    public User getUserLogin(HttpServletRequest request){
        if (request == null) {
            return null;
        }
        Object attribute = request.getSession().getAttribute(USER_LOGIN_STATE);
        if (attribute == null) {
            throw new BusinessException(UNAUTHORIZED);
        }
        return (User) attribute;
    }

    @Override
    public boolean isAdmin(User loginUser) {
        return loginUser != null && loginUser.getUserRole() == ADMIN_ROLE;
    }

}




